from multiprocessing import Process, Manager
import multiprocessing.shared_memory as shm
import numpy as np
import cv2
import json
import time

def producer(lock):
    # barrier.wait()  # 等待消费者就绪
     image1 = cv2.imread(r'aaaa.jpg')
     image2 = cv2.imread(r'aaaa.jpg')
     image3 = cv2.imread(r'aaaa.jpg')
     all_img = np.stack([image1,image2,image3])
     all_img = np.ascontiguousarray(all_img)
    #  size = image.shape[0] * image.shape[1] * image.shape[2]
     meta_dict = {"format": "RGB", "shape": all_img.shape,"size":all_img.nbytes}
     meta_bytes = json.dumps(meta_dict).encode()  # 序列化字典
     print(len(meta_bytes))
     print("all_img.nbytes:",all_img.nbytes)
     shm_img = shm.SharedMemory(name="SyncImg", create=True, size=all_img.nbytes + 1024)  # 480x640x3
     while True:
        with lock:

            # img_np = np.ndarray(image.shape, dtype=np.uint8, buffer=shm_img.buf[:size])
            # img_dict = {"aaa":[1,2,3],
            #             "bbb":{"a":1},
            #             "size":size}
            # shared_dict = img_dict
            # shm_img.buf[:image.nbytes] = image.tobytes()  # 写入图片
            # shm_img.buf[image.nbytes : image.nbytes + len(meta_bytes)] = meta_bytes  # 写入字典

            shm_img.buf[:len(meta_bytes)] = meta_bytes  # 写入图片
            shm_img.buf[len(meta_bytes) : all_img.nbytes + len(meta_bytes)] = all_img.tobytes()   # 写入字典
            # shm_img.buf[size+1:] = bytes(str(img_dict),encoding='utf-8')
            # cv2.imshow("Image", img_np)
            print("hhh")
            # print("222222222222222")
        
            # img_np[:] = image
            print("Producer: 数据写入完成")
            time.sleep(2222)
            # input()  # 模拟持续运行
        shm_img.unlink()

if __name__ == "__main__":
    with Manager() as manager:
        lock = manager.Lock()
        producer(lock)

          